import {
  query as queryUserList,
  create as createUser,
  update as updateUser,
  deleteOne as deleteUser,
} from '@/services/user';
import { message } from 'antd';

const SystemUserModel = {
  namespace: 'systemUser',
  state: {
    users: [],
    total: 0,
    page: 1,
    page_size: 10,
    query: {},
    status: undefined,
  },
  effects: {
    *fetchList({ payload }, { call, put }) {
      const response = yield call(queryUserList, { ...payload });
      yield put({
        type: 'saveListUser',
        payload: {
          data: response.data,
          query: payload,
        },
      });
    },
    *fetchCreate({ payload }, { call, put }) {
      const response = yield call(createUser, { ...payload });
      const newUser = { ...payload };
      if (response.code == 200) {
        newUser.id = response.data.id;
        yield put({
          type: 'saveCreateUser',
          payload: newUser,
        });
      } else {
        message.error(response.msg);
      }
    },
    *fetchUpdate({ payload }, { call, put }) {
      const response = yield call(updateUser, { ...payload });
      if (response.code == 200) {
        newUser.id = response.data.id;
        yield put({
          type: 'saveCreateUser',
          payload: newUser,
        });
        message.info('编辑成功');
      } else {
        message.error(response.msg);
      }
    },
  },
  reducers: {
    saveListUser(state, action) {
      const data = action.payload.data;
      return {
        ...state,
        ...data,
        query: action.payload,
      };
    },
    saveCreateUser(state, action) {
      const newState = state;
      newState.users.unshift(action.payload);
      console.log(newState);
      return {
        ...newState,
      };
    },
    saveDeleteUser(state, action) {
      const newState = state;
      newState.users.unshift(action.payload);
      console.log(newState);
      return {
        ...newState,
      };
    },
  },
};
export default SystemUserModel;
